﻿using System.Collections.Generic;
using JSC.Portal.Entities;
using JSC.Core.Data;
using JSC.Core;
using JSC.Portal.Services;
using System;
using JSC.Core.Security.Cryptography;

namespace JSC.Portal.Data
{
    public class PortalUserService : CommonDao<PortalUser>, IPortalUserService 
    {
        #region IUserDao Members

        public PortalUser Login(string username, string password, DateTime lastlogin, string ip)
        {
            string query = "from PortalUser pu where pu.Username = :username";
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("username", username);
            PortalUser user = GetUniqueByQuery(query, parameters);
            if (user != null && Authentication.Compare(password, user.Password, user.PasswordSalt))
            {
                user.LastLogin = lastlogin;
                user.LastIP = ip;
                user = SaveOrUpdate(user);
                user.IsAuthenticated = true;
            }
            return user;
        }

        public IList<PortalUser> GetSiteUsers(string siteAddress)
        {
            string hql = "from PortalUser pu where lower(pu.PortalSite.Url) = :siteaddress";
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("siteaddress", siteAddress.ToLowerInvariant());
            IList<PortalUser> result = GetByQuery(hql, parameters);
            return result;
        }

        #endregion
    }
}
